﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Web.RS.SBM.AppCode.Lib;
using System.Data;
using System.Data.SqlClient;
using com.Bliss.Services;
using com.Bliss.ServiceFacade.User.Request;
using com.Bliss.ServiceFacade.Post.Request;


namespace mojoPortal.Web.RS.SBM
{
    public partial class RSAdHocInvoice : RSBasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                InitializeReadyServicePage("Create Invoice");

                DateTime dt = DateTime.Now;
                txtDueDate.Text = dt.ToShortDateString();
                UpdateInvoiceItemList();
                RSUserIdentity userIdentity = GetRSUserIdentity();

                lblCompanyName.Text = userIdentity.RSCompanyName;
                litCompanyFullAddress.Text = "<b>" + RSSBMCommonFunctions.GetCompanyFullAddress(userIdentity.RSCompanyId) + "</b>";

                if (Request.QueryString["locationid"] != null)
                {
                    txtJobAddress.Visible = true;
                    int locationid = Convert.ToInt32(Request.QueryString["locationid"].ToString());
                    LoadBillingContactDDL(userIdentity.RSCompanyId, locationid);
                    txtJobAddress.Text = RSSBMCommonFunctions.GetLocationFullAddressByID(userIdentity.RSCompanyId, locationid);
                    txtJobAddress.Visible = true;
                    ddlJobAddress.Visible = false;
                }
                else
                {
                    List<LocationAddress> locaddress = RSSBMCommonFunctions.GetLocationFullAddress(userIdentity.RSCompanyId);
                    ddlJobAddress.Items.Clear();
                    ddlJobAddress.DataSource = locaddress;
                    ddlJobAddress.DataTextField = "fulladdress";
                    ddlJobAddress.DataValueField = "locationid";
                    ddlJobAddress.DataBind();
                    ddlJobAddress.Items.Insert(0, new ListItem("< Please Select >", "0"));
                    ddlJobAddress.Visible = true;
                    txtJobAddress.Visible = false;
                }
            }
        }
        protected void LoadBillingContactDDL(int companyid, int locationid)
        {
            SqlCommand myCommand;
            SqlDataReader myDataReader;
            String sqlSELECT = "select c.contactid, c.lastname + ', ' + c.firstName as name from rs_tblContact c where c.companyid=@companyid and c.contactid in(select cl.contactid from rs_tblcontactlocation cl where cl.locationid=@locationid and cl.companyid=@companyid)  order by LastName, firstname";
            SqlParameter param;
            SqlConnection myConnection;

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[RSSBMCommonFunctions.GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT, myConnection);
            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@locationid";
            param.Value = locationid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            ddlBillingContact.Items.Clear();
            ddlBillingContact.DataSource = myDataReader;
            ddlBillingContact.DataTextField = "name";
            ddlBillingContact.DataValueField = "contactid";
            ddlBillingContact.DataBind();
            ddlBillingContact.Items.Insert(0, new ListItem("< Please Select >", "0"));
            myConnection.Close();
        }

        protected void ddlJobAddress_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            int locationid = Convert.ToInt32(ddlJobAddress.SelectedValue);
            LoadBillingContactDDL(userIdentity.RSCompanyId, locationid);
        }
        protected void ddlBillingContact_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            int contactid = Convert.ToInt32(ddlBillingContact.SelectedValue);
            RSUserIdentity userIdentity = GetRSUserIdentity();
            txtBillingAddress.Text = RSSBMCommonFunctions.GetBillingLocationFullAddress(userIdentity.RSCompanyId, contactid);
        }

        private void UpdateInvoiceItemList()
        {
            AddShoppingPartItemToList();
            AddNewInvoiceItemToList();
            DisplayInvoiceItem();
        }
        private void DisplayInvoiceItem()
        {
            List<InvoiceItem> selInvoiceItems = new List<InvoiceItem>();
            if (Session["INVOICE_ITEMLIST"] != null)
                selInvoiceItems = (List<InvoiceItem>)Session["INVOICE_ITEMLIST"];

            gvInvoiceItems.DataSource = selInvoiceItems;
            gvInvoiceItems.DataBind();

            if (selInvoiceItems.Count > 0)
            {
                for (int i = 0; i < selInvoiceItems.Count; i++)
                {
                    if (selInvoiceItems[i].ItemType == "WorkOrder")
                    {
                        ddlItemType.Items.Remove(ddlItemType.Items.FindByText("WorkOrder"));
                        break;
                    }
                }
            }
        }
        protected void btnAddInvoiceItem_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                if (ddlItemType.SelectedValue == "Part")
                {
                    int locationid = 0;
                    if (Request.QueryString["locationid"] != null)
                        locationid = Convert.ToInt32(Request.QueryString["locationid"].ToString());
                    else
                        locationid = Convert.ToInt32(ddlJobAddress.SelectedValue);

                    if (locationid > 0)
                        Response.Redirect("~/RS/SBM/RSShoppingPart.aspx?locationid=" + locationid);
                }
                else
                {
                    UpdateInvoiceItemList();
                }
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
        }

        private void AddNewInvoiceItemToList()
        {
            string itemtype = ddlItemType.SelectedValue;
            string itemname = txtItemName.Text;
            decimal amount = txtAmount.Text == "" ? 0 : Convert.ToDecimal(txtAmount.Text);
            if (itemtype.Contains("WorkOrder") || itemtype.Contains("Task"))
            {
                List<InvoiceItem> selInvoiceItems = new List<InvoiceItem>();
                if (Session["INVOICE_ITEMLIST"] != null)
                    selInvoiceItems = (List<InvoiceItem>)Session["INVOICE_ITEMLIST"];

                selInvoiceItems.Add(new InvoiceItem(itemtype, itemname, amount, 0, 0));
                Session["INVOICE_ITEMLIST"] = selInvoiceItems;
            }
            ddlItemType.SelectedValue = "";
            txtItemName.Text = "";
            txtAmount.Text = "";
        }

        private void AddShoppingPartItemToList()
        {
            List<ShoppingPart> selParts = new List<ShoppingPart>();
            if (Session["SHOPPING_PARTLIST"] != null)
                selParts = (List<ShoppingPart>)Session["SHOPPING_PARTLIST"];

            if (selParts.Count > 0)
            {
                string itemname;
                decimal unitprice;
                decimal amount;
                int productid = 0;
                int quantity = 0;

                List<InvoiceItem> selInvoiceItems = new List<InvoiceItem>();
                if (Session["INVOICE_ITEMLIST"] != null)
                    selInvoiceItems = (List<InvoiceItem>)Session["INVOICE_ITEMLIST"];

                for (int i = 0; i < selParts.Count; i++)
                {
                    itemname = selParts[i].ProductName;
                    unitprice = selParts[i].UnitPrice;
                    productid = Convert.ToInt32(selParts[i].ProductId);
                    quantity = Convert.ToInt32(selParts[i].Quantity);
                    amount = quantity * unitprice;
                    selInvoiceItems.Add(new InvoiceItem("Part", itemname, amount, quantity, unitprice, productid));
                }
                Session["INVOICE_ITEMLIST"] = selInvoiceItems;
            }
            Session["SHOPPING_PARTLIST"] = null;
        }

        protected void ddlItemType_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            string itemtype = ddlItemType.SelectedValue;
            if (itemtype.Contains("WorkOrder") || itemtype.Contains("Task"))
            {
                txtItemName.Enabled = true;
                txtAmount.Enabled = true;
                txtItemName.BackColor = System.Drawing.Color.White;
                txtAmount.BackColor = System.Drawing.Color.White;
                btnAddInvoiceItem.Enabled = true;
            }
            else
            {
                txtItemName.Enabled = false;
                txtAmount.Enabled = false;
                txtItemName.BackColor = System.Drawing.Color.Gainsboro;
                txtAmount.BackColor = System.Drawing.Color.Gainsboro;
                if (itemtype.Contains("Part"))
                    btnAddInvoiceItem.Enabled = true;
                else
                    btnAddInvoiceItem.Enabled = false;
            }
        }

        protected void btnResetInvoiceItem_OnClick(object sender, EventArgs e)
        {
            Session["INVOICE_ITEMLIST"] = null;
            DisplayInvoiceItem();
        }

        protected void gvInvoiceItems_Remove(Object sender, CommandEventArgs e)
        {
            string item = e.CommandArgument.ToString();
            RemoveSelectedItemFromList(item);
            DisplayInvoiceItem();
        }

        private void RemoveSelectedItemFromList(string item)
        {
            List<InvoiceItem> selItems = new List<InvoiceItem>();
            if (Session["INVOICE_ITEMLIST"] != null)
                selItems = (List<InvoiceItem>)Session["INVOICE_ITEMLIST"];

            if (selItems.Count > 0)
            {
                for (int i = 0; i < selItems.Count; i++)
                {
                    if (selItems[i].ItemName == item)
                    {
                        selItems.RemoveAt(i);
                        break;
                    }
                }
            }
            Session["INVOICE_ITEMLIST"] = selItems;
        }
        protected void btnCreateInvoice_OnClick(object sender, EventArgs e)
        {
            List<InvoiceItem> selItems = new List<InvoiceItem>();
            if (Session["INVOICE_ITEMLIST"] != null)
                selItems = (List<InvoiceItem>)Session["INVOICE_ITEMLIST"];

            if (selItems.Count > 0)
            {
                int locationid = 0;
                if (Request.QueryString["locationid"] != null)
                    locationid = Convert.ToInt32(Request.QueryString["locationid"].ToString());
                else
                    locationid = Convert.ToInt32(ddlJobAddress.SelectedValue);

                if (locationid > 0)
                {
                    int workorderid = 0;
                    string workordername = string.Empty;
                    string taskname = string.Empty;
                    int quantity = 0;
                    int productid = 0;
                    decimal laborcost = 0;
                    for (int i = 0; i < selItems.Count; i++)
                    {
                        if (selItems[i].ItemType == "WorkOrder")
                        {
                            workordername = selItems[i].ItemName;
                            laborcost = selItems[i].Amount;
                            workorderid = SaveWorkOrder(locationid, workordername, laborcost);
                            break;
                        }
                    }
                    if (workorderid > 0)
                    {
                        for (int j = 0; j < selItems.Count; j++)
                        {
                            if (selItems[j].ItemType == "Task")
                            {
                                taskname = selItems[j].ItemName;
                                laborcost = selItems[j].Amount;
                                SaveWorkOrderTask(locationid, workorderid, taskname, laborcost);
                            }
                            if (selItems[j].ItemType == "Part")
                            {
                                quantity = selItems[j].Quantity;
                                productid = selItems[j].ProductId;
                                SaveWorkOrderPart(locationid, workorderid, quantity, productid);
                            }
                        }
                        if (CreateAdHocInvoice(locationid, workorderid) > 0)
                            ucModalActionMessageControl.ShowModal("Invoice Created Successfully!", "~/RS/SBM/RSLocationHistoryInvoices.aspx?locationid=" + locationid, true);
                        else
                            ucModalActionMessageControl.ShowModal("Invoice Could Not Be Created.  Please Check With System Administrator.", "", false);
                    }
                }

                //////////////////Start Code for Posting a Wall Post in Company Wall.
                int botuserID = 0;
                RSUserIdentity userIdentity = GetRSUserIdentity();
                IUserService userService = new UserService();
                var botUser = userService.GetBotUser(new GetUsersRequest() { CompanyId = userIdentity.RSCompanyId });
                if (botUser.Data == null)
                {
                    // Throw / Log error for Not having BOT user for selected CompanyID.
                }
                else
                {
                    botuserID = botUser.Data.ID;
                    string scrap = "Sample Scrap for new Invoice created To the selected Company's Wall";
                    IPostService service = new PostService();
                    service.Post(new PostRequest { FromUserID = botuserID, ToPostID = null, Message = scrap, GroupId = null });
                }
                //////////////////End Code for Posting a Wall Post in Company Wall.
            }
        }

        private int SaveWorkOrder(int locationid, string workordername, decimal laborcost)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            string additionalinstruction = txtAdditionalInstruction.Text;
            string terms = txtTerms.Text;
            string invoiceno = txtInvoiceNum.Text;
            string pono = txtPONum.Text;
            int billingcontactid = Convert.ToInt32(ddlBillingContact.SelectedValue);
            SqlCommand sqlCmd = new SqlCommand();

            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderName", SqlDbType.NVarChar, 150, ParameterDirection.Input, workordername);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LaborCost", SqlDbType.Decimal, 0, ParameterDirection.Input, laborcost);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@AdditionalInstructions", SqlDbType.NVarChar, 250, ParameterDirection.Input, additionalinstruction);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Terms", SqlDbType.NVarChar, 250, ParameterDirection.Input, terms);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@InvoiceNo", SqlDbType.NVarChar, 10, ParameterDirection.Input, invoiceno);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@PONumber", SqlDbType.NVarChar, 50, ParameterDirection.Input, pono);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@BillingContactId", SqlDbType.Int, 0, ParameterDirection.Input, billingcontactid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationId", SqlDbType.Int, 0, ParameterDirection.Input, locationid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, userIdentity.RSCompanyId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@IsAdHoc", SqlDbType.Bit, 0, ParameterDirection.Input, 1);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@IsInvoiced", SqlDbType.Bit, 0, ParameterDirection.Input, 1);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
            SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveWorkOrder");
            SQLHelper.ExecuteScalarCmd(sqlCmd);
            int workorderid = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
            return workorderid;
        }
        private void SaveWorkOrderTask(int locationid, int workorderid, string taskname, decimal laborcost)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            SqlCommand sqlCmd = new SqlCommand();
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@TaskName", SqlDbType.NVarChar, 100, ParameterDirection.Input, taskname);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LaborCost", SqlDbType.Decimal, 0, ParameterDirection.Input, laborcost);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderId", SqlDbType.Int, 0, ParameterDirection.Input, workorderid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationId", SqlDbType.Int, 0, ParameterDirection.Input, locationid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, userIdentity.RSCompanyId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
            SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveWorkOrderTask");
            SQLHelper.ExecuteScalarCmd(sqlCmd);
            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
        }
        private void SaveWorkOrderPart(int locationid, int workorderid, int quantity, int productid)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            SqlCommand sqlCmd = new SqlCommand();
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@quantity", SqlDbType.Int, 0, ParameterDirection.Input, quantity);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@productid", SqlDbType.Int, 0, ParameterDirection.Input, productid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderid", SqlDbType.Int, 0, ParameterDirection.Input, workorderid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, userIdentity.RSCompanyId);
            SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "INSERT INTO rs_tblWorkOrderPart (WorkOrderid, productid, quantity, companyid, unitprice) VALUES(@WorkOrderid, @productid, @quantity, @companyid, (select i.unitprice from rs_tblInventory i where i.productid=@productid and i.companyid=@companyid))");
            SQLHelper.ExecuteScalarCmd(sqlCmd);
            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
        }
        private int CreateAdHocInvoice(int locationid, int workorderid)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            string invoiceno = txtInvoiceNum.Text;
            string dueDate = txtDueDate.Text;
            int taxpercent = txtTax.Text == "" ? 0 : int.Parse(txtTax.Text);
            SqlCommand sqlCmd = new SqlCommand();
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderId", SqlDbType.Int, 0, ParameterDirection.Input, workorderid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationId", SqlDbType.Int, 0, ParameterDirection.Input, locationid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, userIdentity.RSCompanyId);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@IsAdHoc", SqlDbType.Bit, 0, ParameterDirection.Input, 1);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@TaxPercent", SqlDbType.Int, 0, ParameterDirection.Input, taxpercent);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@DueDt", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(dueDate));
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@InvoiceNo", SqlDbType.NVarChar, 10, ParameterDirection.Input, invoiceno);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
            SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveInvoice");
            SQLHelper.ExecuteScalarCmd(sqlCmd);
            int invoiceid = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
            return invoiceid;
        }
    }
}